<?php

namespace app\admin\model;

use think\Db;
use think\Model;
use app\admin\model\AdminModel;

class RegionModel extends Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getRegion($map = array(), $field = '*', $order = 'region_id asc')
    {
        $areaInfo = AdminModel::getRoleArea();
        $list = Db::name('region')->where($map)->order($order)->field($field.',region_level')->select();
        if(!empty($areaInfo['admin_type']) && $areaInfo['admin_type'] != 1){
            foreach ($list as $key=>$value){
                if(!empty($areaInfo['province']) && !in_array($value['region_id'],$areaInfo['province']) && $value['region_level'] == 1){
                    unset($list[$key]);
                }elseif(!empty($areaInfo['city']) && !in_array($value['region_id'],$areaInfo['city']) && $value['region_level'] == 2){
                    unset($list[$key]);
                }
            }
        }
        return $list;
    }

    //查询省份城市
    public function getRegionList()
    {
        $prolist = Db::name('region')->where(['region_level' => 1])->order('region_id', 'asc')->field('region_id,region_code,region_name')->select();
        $franchiseeList = [];
        foreach ($prolist as $key => $value) {
            //查询每个省下面的加盟商信息统计
            $franchiseeList = Db::name('franchisee')->where(['province_id' => $value['region_id'], 'is_del' => 1])->field('id,franchisee_name')->select();
            if (!empty($franchiseeList)) {
                $prolist[$key]['number'] = count($franchiseeList);
                foreach ($franchiseeList as $kk => $val) {
                    $franchiseeList[$kk]['franchisee_name'] = mb_substr($val['franchisee_name'], 0, 6, 'utf-8');
                }
                $prolist[$key]['CHILD'] = $franchiseeList;
            } else {
                unset($prolist[$key]);
            }
        }
        return $prolist;
    }
}
